package com.example.wisdomclassroomapi.facade.filter;

import com.example.wisdomclassroomapi.facade.security.RequestAuthenticationDetails;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FormLoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        // 创建未认证凭证
        UsernamePasswordAuthenticationToken usernamePasswordToken = new UsernamePasswordAuthenticationToken("占位", "占位");

        // 将认证详情（ IP，sessionId， username, password captcha 验证码，captchaId 验证码Id ）写到凭证
        try {
            usernamePasswordToken.setDetails(new RequestAuthenticationDetails(request));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }

        // 跳转到JwtAuthenticationProvider.authenticate 方法中认证
        return this.getAuthenticationManager().authenticate(usernamePasswordToken);
    }
}
